function save_nifti(mat,filename,type)
[path,name]=fileparts(filename);
new_mat=zeros(size(mat,2),size(mat,1),size(mat,3));
for i=1:size(new_mat,3)
    new_mat(:,:,i)=(imrotate(mat(:,:,i),180))';
end    
nii.untouch=1;
nii.fileprefix=[path,'\',name];
nii.machine='ieee-le';
nii.ext=[];
nii.filetype=2;
nii.hdr.hk.sizeof_hdr=348;
nii.hdr.hk.data_type='';
nii.hdr.hk.db_name='';
nii.hdr.hk.extents=0;
nii.hdr.hk.session_error=0;
nii.hdr.hk.regular='r';
nii.hdr.hk.dim_info=0;
nii.hdr.dime.dim=[length(size(mat)) size(mat,1) size(mat,2) size(mat,3) 1 1 1 1];
nii.hdr.dime.intent_p1=0;
nii.hdr.dime.intent_p2=0;
nii.hdr.dime.intent_p3=0;
nii.hdr.dime.intent_code=0;
nii.hdr.dime.slice_start=0;
nii.hdr.dime.pixdim=[-1 1 1 1 0 0 0 0];
nii.hdr.dime.vox_offset=352;
nii.hdr.dime.scl_slope=0;
nii.hdr.dime.scl_inter=0;
nii.hdr.dime.slice_end=0;
nii.hdr.dime.slice_code=0;
nii.hdr.dime.xyzt_units=0;
nii.hdr.dime.cal_max=0;
nii.hdr.dime.cal_min=0;
nii.hdr.dime.slice_duration=0;
nii.hdr.dime.toffset=0;
nii.hdr.dime.glmax=1;
nii.hdr.dime.glmin=0;
nii.hdr.hist.descrip='spm - realigned';
nii.hdr.hist.aux_file='';
nii.hdr.hist.qform_code=2;
nii.hdr.hist.sform_code=2;
nii.hdr.hist.quatern_b=0;
nii.hdr.hist.quatern_c=0;
nii.hdr.hist.quatern_d=0;
nii.hdr.hist.qoffset_x=0;
nii.hdr.hist.qoffset_y=0;
nii.hdr.hist.qoffset_z=0;
nii.hdr.hist.srow_x=[0 0 0 0];
nii.hdr.hist.srow_y=[0 0 0 0];
nii.hdr.hist.srow_z=[0 0 0 0];
nii.hdr.hist.intent_name='';
nii.hdr.hist.magic='n+1';
if (type==1)
    nii.img=uint16(new_mat);
    nii.hdr.dime.datatype=4;
    nii.hdr.dime.bitpix=16;
    save_untouch_nii(nii,filename);
    return
else
    if (type==2)
    nii.img=uint8(new_mat);
    nii.hdr.dime.datatype=2;
    nii.hdr.dime.bitpix=8;  
    save_untouch_nii(nii,filename);
    return
    end
end
disp('Type parameter must be 1 or 2!');

    
    
    
    
    